package ch.subgate.pongwars;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;

public class GameActivity extends Activity {
	
	private GameView mGameView;
	
	private GameThread mGameThread;

    private BluetoothAdapter mBluetoothAdapter = null;

    private BluetoothSocket mBluetoothSocket = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gameactivity_layout);

        // Set audio stream
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

        // Check the calling intent for settings
        Intent i = this.getIntent();
        int mode = i.getIntExtra("mode", Constants.MODE_PVE);
        float size = i.getFloatExtra("size", Constants.PADDLE_EASY);
        float volume = i.getFloatExtra("volume", 1.0f);
        boolean isServer = i.getBooleanExtra("role", true);
        String addr = i.getStringExtra("mac");

        // Get the instances of GameView and GameThread and get started
        mGameView = (GameView)findViewById(R.id.gameview);
        mGameThread = mGameView.getThread();
        mGameThread.setGameMode(this, mode, size, isServer, volume);

        if (mode == Constants.MODE_PVPN) { // this is a bluetooth multiplayer game
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (isServer) {
                // make device discoverable
                startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE));
                // open server socket
                Thread t = new AcceptThread(this);
                t.start();
            } else {
                // open client socket
                Thread t = new ConnectThread(addr, this);
                t.start();
            } // if
        } else { // this is a local single- or multiplayer game, therefore we can start immediately
            mGameThread.setRunning(true);
            mGameThread.start();
        } // if
	} // onCreate

    /**
     * Will set the bluetooth socket for the GameThread and start the thread. This method is getting
     * called either from ConnectThread or AcceptThread in order to minimize blocking on the UI
     * thread.
     * @param socket The connected or connecting bluetooth socket
     */
    public void manageConnectedSocket(BluetoothSocket socket) {
        if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); }
        mBluetoothSocket = socket;
        ((GameContextP2P)mGameThread.getGameContext()).setSocket(mBluetoothSocket);
        mGameThread.setRunning(true);
        mGameThread.start();
    } // manageServerSocket
} // GameActivity
